﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.ProductionManage;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services; // 新增

namespace ProduceBasicData.Api.Application.Handler.ProductionManage
{
    public class CreateWorkCommandHandler : IRequestHandler<CreateWorkCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Work_order> workRespository;
        private readonly ICodeRuleService codeRuleService; // 新增
        private readonly IMapper mapper;

        public CreateWorkCommandHandler(
            IBaseRespository<Work_order> workRespository,
            ICodeRuleService codeRuleService, // 新增
            IMapper mapper)
        {
            this.workRespository = workRespository;
            this.codeRuleService = codeRuleService; // 新增
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(CreateWorkCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>() { Code = ApiEnum.Success, Msg = "添加生产工单成功" };
            using (var tarn = workRespository.DB.Database.BeginTransaction())
            {
                try
                {
                    var time = DateTime.Now;
                    var info = mapper.Map<Work_order>(request);
                    info.Status = 1;
                    info.CreateName = request.CreateName;
                    info.CreateTime = time;

                    // 新增：自动生成工单编码
                    if (string.IsNullOrEmpty(info.Order_no))
                    {
                        var generatedCode = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.ProductionManage.Work_order");
                        if (!string.IsNullOrEmpty(generatedCode))
                        {
                            info.Order_no = generatedCode;
                        }
                        else
                        {
                            // 如果没有配置规则，使用默认生成方式
                            info.Order_no = $"WO{DateTime.Now:yyyyMMddHHmmss}";
                        }
                    }

                    await workRespository.AddAsync(info);
                    tarn.Commit();
                }
                catch (Exception ex)
                {
                    result = new ApiResult<int>() { Code = ApiEnum.Failed, Msg = "添加生产工单失败" };
                    tarn.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
}